﻿// ********************************************************************
//  文件名: MyTcpClient.cs
//  描述:
//  作者: 胡宇辰
//  创建时间: 2024-3-19
// 
//  修改历史:
// ********************************************************************

using System.Net;
using System.Net.Sockets;

namespace MyApp;

public class MyTcpClient
{
    static TcpClient _client;

    public static void Enter()
    {
        //客户端利用socket连接服务器
        _client = new TcpClient();
        try
        {
            _client.Connect("127.0.0.1", 6324);
            Console.WriteLine("连接成功");
            var sendThread = new Thread(SendMsg);
            sendThread.IsBackground = true;
            sendThread.Start();

            var receiveThread = new Thread(ReceiveMsg);
            receiveThread.IsBackground = true;
            receiveThread.Start();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }

    static void SendMsg()
    {
        byte[] buffer = new byte[1024];
        //向服务器发送数据
        while (true)
        {
            string? str = Console.ReadLine();
            int count = System.Text.Encoding.UTF8.GetBytes(str!, buffer);
            _client.GetStream().Write(buffer, 0, count);
        }
    }

    static void ReceiveMsg()
    {
        var buffer = new byte[1024];
        while (true)
        {
            int length = _client.GetStream().Read(buffer, 0, buffer.Length);
            if (length > 0)
            {
                Console.WriteLine($"{System.Text.Encoding.UTF8.GetString(buffer, 0, length)}");
            }
            else
            {
                Console.WriteLine($"退出");
                break;
            }
        }
    }
}